package com.dalu.app.ui


import android.Manifest
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.KeyEvent
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Toast
import com.dalu.app.R
import com.dalu.app.utils.LocationUtils
import com.dalu.app.utils.LogT
import com.dalu.app.utils.PermissionUtils
import com.dalu.app.utils.SpUtils
import kotlinx.android.synthetic.main.activity_base_web_view.*
import pub.devrel.easypermissions.AppSettingsDialog
import pub.devrel.easypermissions.EasyPermissions
import java.util.ArrayList

class BaseWebView : BaseActivity() ,EasyPermissions.PermissionCallbacks {


    private var baseUrl: String = "http://47.97.106.106:8001/login"
    override fun getLayoutResouse(): Int {

        return R.layout.activity_base_web_view
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestPermission()
    }

    private fun requestPermission() {
        if (EasyPermissions.hasPermissions(this, *PermissionUtils.permissions)) {
        } else {
            EasyPermissions.requestPermissions(this, "APP正常运行需要申请部分权限,请允许权限", PermissionUtils.REQUEST_PERMISSION_CODE, *PermissionUtils.permissions)
        }

    }

    @SuppressLint("SetJavaScriptEnabled")
    override fun initView() {



        var url = intent.getStringExtra("url")
        url = url ?: baseUrl

        webView?.loadUrl(url)

        val webSettings = webView?.settings

        // 设置与Js交互的权限
        webSettings?.javaScriptEnabled = true

        webView?.webViewClient = object : WebViewClient() {

            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                view?.loadUrl(url)
                return true
            }


            override fun onPageFinished(view: WebView?, url: String?) {
                url?.let {
                    if (url.contains("http://47.97.106.106:8001/index")) {
//                        webView?.loadUrl("http://47.97.106.106:8001/index"+"?lat=${SpUtils.getLatitude()}"+"&long=${SpUtils.getLongitude()}")
                        LogT.d("调用js方法")
                        webView?.loadUrl("javascript:logLat(" + "'${SpUtils.getLongitude()}','${SpUtils.getLatitude()}'" + ")")

                    }
                }

            }


        }

        startLocation()
    }

    private fun startLocation() {
        val location = LocationUtils.getInstance(this).showLocation()
        if (location != null) {
            val address = "纬度：" + location.latitude + "经度：" + location.longitude
            SpUtils.putLatitude(location.latitude.toString())
            SpUtils.putLongitude(location.longitude.toString())
            LogT.d(address)
        }
    }


//    点击返回上一页面而不是退出浏览器

//    private var latestTime: Long = 0

//    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            if (webView!!.canGoBack()) {
//                webView.goBack()
//            } else {
//                if (System.currentTimeMillis() - latestTime > 2000) {
//                    Toast.makeText(this, "再次点击退出", Toast.LENGTH_LONG).show()
//                    latestTime = System.currentTimeMillis()
//                } else {
//                    finish()
//                }
//            }
//
//        }
//        return true
//
//    }




    private var latestTime: Long = 0

    override fun onBackPressed() {
            if (System.currentTimeMillis() - latestTime > 2000) {
                Toast.makeText(this, "再次点击退出", Toast.LENGTH_LONG).show()
                latestTime = System.currentTimeMillis()
                return
            } else {
                finish()
            }
        super.onBackPressed()

    }





    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }



    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
        val permissions = ArrayList<String>()
        permissions.add(Manifest.permission.ACCESS_FINE_LOCATION)

        if (EasyPermissions.somePermissionPermanentlyDenied(this, permissions)) {
            AppSettingsDialog.Builder(this)
                    .setTitle(R.string.permission_title)
                    .setRationale(R.string.permission_request)
                    .setPositiveButton(R.string.rationale_ask_ok)
                    .setNegativeButton(R.string.rationale_ask_cancel)
//                    .setThemeResId(R.style.permissions_dialog)
                    .build().show()
        }

    }

    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
        startLocation()

    }


    override fun onDestroy() {
        LocationUtils.getInstance(this).removeLocationUpdatesListener()
        super.onDestroy()

    }
}



